package com.cgutech.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NettyClients  {

    private Map<String, NettyClient> clients = new HashMap<String, NettyClient>();

    public NettyClients(){
    }

    public void start(List<DeviceConnectData> devices) {
        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup group;
        String windowsName = System.getProperties().getProperty("os.name").toLowerCase();
        Class<? extends Channel> channelClass;
        if(windowsName.contains("windows")) {
            group = new NioEventLoopGroup();
            channelClass = NioSocketChannel.class;
        } else {
            group = new EpollEventLoopGroup();
            channelClass = EpollSocketChannel.class;
        }
        bootstrap.group(group).channel(channelClass).option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
               //  System.out.println("新连接");
            }
        });

        for(DeviceConnectData device : devices) {
            NettyClient client = new NettyClient(device, bootstrap, device.getUid());
            try {
                client.connect();
                clients.put(device.getUid(), client);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void close() {
        for(Map.Entry<String, NettyClient> entry : clients.entrySet()) {
            entry.getValue().close();
        }
    }

    public void send(byte[] data) {
        for(Map.Entry<String, NettyClient> entry : clients.entrySet()) {
            entry.getValue().write(data);
        }
    }

    public void send(String id, byte[] data) {
        if(clients.containsKey(id)) {
            clients.get(id).write(data);
        }
    }
}
